package com.bwie.service.impl;

import com.bwie.exception.BusinessException;
import com.bwie.mapper.MenuMapper;
import com.bwie.pojo.Result;
import com.bwie.pojo.po.MenuPo;
import com.bwie.pojo.po.UserPo;
import com.bwie.service.MenuService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ 权限
 * @descriptions: MenuServiceImpl
 * @author: LiYang
 * @date: 2025/3/14 15:01
 * @version: 1.0
 */
@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private HttpServletRequest request;
    @Override
    public Result getMenu() {
        UserPo user  = (UserPo) request.getSession().getAttribute("user");
        if(ObjectUtils.isEmpty(user)){
            throw new BusinessException("未注册，请先去登录");
        }
        List<MenuPo> list=menuMapper.selectUserId(user.getUserId());

        List<MenuPo> menuPoList=getMenuList(list);
        return Result.success("查询成功",menuPoList);
    }

    private List<MenuPo> getMenuList(List<MenuPo> list) {
        Map<Integer, List<MenuPo>> map = list.stream().collect(Collectors.groupingBy(MenuPo::getParentId));
        List<MenuPo> children=findIdList(-1,map);
        return children;
    }

    private List<MenuPo> findIdList(int pid, Map<Integer, List<MenuPo>> map) {
        List<MenuPo> menuPoList = map.get(pid);
        if(menuPoList!=null && menuPoList.size()>0){
            for (MenuPo menuPo : menuPoList) {
                List<MenuPo> idList = findIdList(menuPo.getMenuId(), map);
                menuPo.setChildrenList(idList);
            }
        }
        return menuPoList;
    }
}
